package fun.lifepoem.demo.aspect;

import fun.lifepoem.demo.annotation.RequireRole;
import fun.lifepoem.demo.common.SessionManager;
import fun.lifepoem.demo.common.UserThreadLocal;
import fun.lifepoem.demo.domain.UserInfo;
import fun.lifepoem.demo.exception.NotRoleException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Yiwyn
 * @create 2022/12/4 1:28
 */
@Aspect
@Component
public class PreAuthorizeAspect {

    public PreAuthorizeAspect() {
    }

    @Pointcut("@annotation(fun.lifepoem.demo.annotation.RequireRole)")
    public void pointCut() {

    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        RequireRole annotation = signature.getMethod().getAnnotation(RequireRole.class);
        String[] value = annotation.value();

        UserInfo userInfo = SessionManager.get();
        List<String> roles = userInfo.getRoles();

        boolean pass = false;

        for (String s : value) {
            boolean contains = roles.contains(s);
            if (contains) {
                pass = true;
                break;
            }
        }
        if (!pass) {
            throw new NotRoleException("无权限");
        }

        Object proceed = joinPoint.proceed();
        return proceed;
    }
}
